<?php
namespace app\crm\model;

use think\Model;
use think\Db;
use think\Cache;
use think\Lang;
// 设定当前语言
Lang::range('zh-cn');

class Role extends Model
{
    /**
     * 缓存角色信息
     */
    protected function rolecache ()
    {
        $result = Db::name('sys_role')->select();
        // 以工号为键
        foreach ($result as $val) {
            $role[$val['r_id']] = $val;
        }
        Cache::set('role', $role);
    }


	/**
     * 实现添加角色的功能
     * @param  [array] $data     [插入数据]
     * @return [int/bool]        [新增主键/false]
     */
	public function insertRole($data)
	{
		$role_count = Db::name('sys_role')->where("r_name='". $data["r_name"] ."'")->count();
		if( $role_count>0 ){
				echo json_encode(array('msg'=>"此角色名已存在！不能重复添加."));
				exit;
		}
		$result = Db::name('sys_role')->insert($data);
        $this->rolecache();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'角色添加成功！'));
        } else {
            echo json_encode(array('msg'=>'角色添加失败！'));
        }
    }

    /**
     * 实现更新角色的功能
     * @param  [array] $data     [插入数据]
     * @return [int/bool]        [新增主键/false]
     */
	public function updateRole($r_id,$data)
	{
		$result = Db::name('sys_role')->where('r_id', $r_id)->update($data);
        $this->rolecache();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'角色更新成功！'));
        } else {
            echo json_encode(array('msg'=>'角色更新失败！'));
        }
    }

    /**
     * 删除角色
     * @param  str $r_id [权限id]
     * @return [type]           [description]
     */
    public function delRole($r_id)
    {
        $result = Db::name('sys_role')->where('r_id',$r_id)->delete();
        $this->rolecache();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'角色删除成功！'));
        } else {
            echo json_encode(array('msg'=>'角色删除失败！'));
        }
    
    }
	
	/**
     * 获取角色列表
     */
    public function getRoleList(){
        $roleList = Db::name('sys_role')->field("r_id,r_name")->select();
        return $roleList;
    }
	
	/**
     * 获取角色资料列表
     * @param int $page <页码>
     * @param int $limit <每页显示条数>
     * @return array <角色列表信息>
     */
	public function getRoleData($page,$limit)
	{
		$count = Db::name('sys_role')->count();
		// 查询状态为1的用户数据 并且每页显示10条数据
        $roleList = Db::name('sys_role')->field("r_id,r_name,description")->limit(($page-1)*$limit,$limit)->select();
		//echo Db::name('role')->getLastSql();die;
		$rowsList = count($roleList) ? $roleList : false;
		$arrRole["code"] = 0;
        $arrRole["msg"] = '';
        $arrRole["count"] = $count;
		$arrRole["data"] = $rowsList;
		return $arrRole;
	}


	/**
     * 数据库读取菜单
     * @param  [arr] $arrPriv [权限]
     * @return [json]          [树形菜单]
     */
    public function roleTree($arrPriv)
    {
        //从数据库中读取菜单
        $tpl_menu = Array();
        $where = "me.pid=0 AND enabled='Y'";
        $mainMenu = Db::table('xy_sys_menu')->field("me.id AS id,name,moduleclass,order,me.pid AS pid,privilege")->alias('me')->join('sys_module mo','me.moduleclass=mo.modulename')->where($where)->order("`order` ASC")->select();
        //dump($mainMenu);die;
        $i = 0;
        foreach( $mainMenu AS $row ){
            $tpl_menu[$i] = Array();
            //直接在php代码中处理一切模版显示的内容，这样比在模版中灵活多了
            $mainId = $row['id'];//一级菜单id
            $mainText = $row['name'];//一级菜单标题
            
            $tpl_menu[$i]['id'] = $mainId;
            $tpl_menu[$i]['state'] = 'closed';     //打开页面时 一级标题全部折叠
            $tpl_menu[$i]['text'] = Lang::get($mainText);  //翻译
            $tpl_menu[$i]['children'] = Array();
            
            $subMenu = Db::table('xy_sys_menu')->field("me.id AS id,name,moduleclass,order,me.pid AS pid,privilege")->alias('me')->join('sys_module mo','me.moduleclass=mo.modulename')->where("me.pid=$mainId AND enabled='Y' ")->order("`order` ASC")->select();
            $j = 0;
            foreach($subMenu AS $arrRow){
                $arrTmp2 = array();//---------------------------------------临时数组
                $subId = $arrRow['id'];//二级菜单id
                $subText = $arrRow['name'];//二级菜单标题
                
                $arrTmp2['id'] = $subId;
                //$arrTmp2['text'] = L($subText);
                $arrTmp2['text'] = Lang::get($subText);
                $arrTmp2['state'] = 'closed';   //打开页面时 点击一级标题后 二级标题全部折叠
                $arrTmp2['children'] = Array();
                //最小 子权限 列表框的显示
                $k = 0;
                $arrP = explode(',',$arrRow['privilege']);//---------------------------------------临时数组
                foreach($arrP AS $v){
                    //echo $arrPriv[$i]['children'][$j]['children'][$k]["checked"];
                    if(isset($arrPriv[$mainText][$subText])){
                        if( $arrPriv[$mainText][$subText][$v] == 'Y' ){
                            $checked = true;//从【权限数组】中判断
                        }else{
                            $checked = false;
                        }
                    }else{
                        $checked = false;
                    }
                    $arrTmp3 = array(//---------------------------------------临时数组
                        //"id" => $subId ."_". $v,
                        "id" => $v,
                        //"text" => L($v),//翻译
                        "text" => Lang::get($v),//翻译
                        "iconCls"=>$v,
                        "checked" => $checked,
                    );
                    $arrTmp2['children'][$k] = $arrTmp3;
                    $k++;
                }
                $tpl_menu[$i]['children'][$j] = $arrTmp2;//把子菜单赋值给父菜单
                $j++;
            }
            $i++;
        }
        $strJSON = json_encode( $tpl_menu,true );
        return $strJSON;
    }

    //角色的相关权限
    public function getRoleArr($r_id)
    {
        $arrRole = Db::name('sys_role')->where('r_id',$r_id)->find();
        return $arrRole;
    }

    /**
     * 更新角色权限
     * @param  [int] $r_id [description]
     * @param  [json] $json [description]
     * @return [type]       [description]
     */
    public function savePriv($r_id,$json)
    {
        $arrJSON = json_decode($json,true);
        //构造一张一维数组$menuList: "id" =>"name" 的键值对
        $menuList = Array();
        $where = "me.pid=0 AND enabled='Y'";
        $arrMenu = Db::table('xy_sys_menu')->field("me.id AS id,name")->alias('me')->join('sys_module mo','me.moduleclass=mo.modulename')->where("enabled='Y'")->order("`order` ASC")->select();
        foreach( $arrMenu As $row ){
            $menuList[$row['id']] = $row['name'];
        }
        $arrPriv = Array();
        $allNoChecked1 = true;//初始化【父菜单】都没选择
        foreach($arrJSON AS $val1){
            $mainId = $val1['id'];//父菜单ID
            $mainName = $menuList[$mainId];
            //$arrPriv[$mainName] = Array();//存储子菜单==============================
            $arrSub = Array();
            $allNoChecked2 = true;//初始化【子菜单】都没选择
            foreach( $val1["children"] AS $val2 ){
                $subId = $val2['id'];//子菜单ID
                $subName = $menuList[$subId];
                        //$arrPriv[$mainName] = Array();//========================
                        $arrP = Array();
                        $allNoChecked3 = true;//初始化【权限】都没有
                        foreach( $val2["children"] AS $val3 ){
                            if( $val3["checked"] == true ){
                                $arrP[$val3['id']] = 'Y';
                                $allNoChecked3 = false;
                            }
                        }
                if( $allNoChecked3 == false && $arrP ){//如果有子菜单选中，都没选中就不要管它
                    $arrSub[$subName] = $arrP;
                    $allNoChecked2 = false;
                }
            }
            if( $allNoChecked2 == false && $arrSub){//如果二级菜单有选中的，但不一定是全选
                $arrPriv[$mainName] = $arrSub;
                $allNoChecked1 = false;
            }
        }
        $strPriv = json_encode($arrPriv);
        $res = Db::table('xy_sys_role')->where("r_id = '$r_id'")->update( array("action_list"=>$strPriv) );
        if(false !== $res){
            $this->rolecache();
             echo json_encode(array('success'=>true,'msg'=>'授权成功！'));
        }else{
             echo json_encode(array('msg'=>'未知错误！'));
        }

    }
	
	
	
	
	
	



}